package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.admin.Analysis;
import com.tanhua.model.vo.CountVo;
import com.tanhua.model.vo.LastYear;
import com.tanhua.model.vo.ThisYear;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Service
public class AnalysisService {

    @Autowired
    private AnalysisMapper analysisMapper;

    @Autowired
    private LogMapper logMapper;

    /**
     * 定时统计日志数据到统计表中
     * 1、查询tb_log表中的数 （每日注册用户数，每日登陆用户，活跃的用户数据，次日留存的用户）
     * 2、构造AnalysisByDay对象
     * 3、完成统计数据的更新或者保存
     */
    public Analysis analysis() throws ParseException {
        //1、定义查询的日期
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesdayStr = DateUtil.yesterday().toString("yyyy-MM-dd");
        //2、统计数据-注册数量
        Integer regCount = logMapper.queryByTypeAndLogTime("0102", todayStr);
        //3、统计数据-登录数量
        Integer loginCount = logMapper.queryByTypeAndLogTime("0101", todayStr);
        //4、统计数据-活跃数量
        Integer activeCount = logMapper.queryByLogTime(todayStr);
        //5、统计数据-次日留存
        Integer numRetention1d = logMapper.queryNumRetention1d(todayStr, yesdayStr);
        //6、根据日期查询数据
        QueryWrapper<Analysis> qw = new QueryWrapper<Analysis>();
        qw.eq("record_date", new SimpleDateFormat("yyyy-MM-dd").parse(todayStr));
        //7、构造Analysis对象
        Analysis analysis = analysisMapper.selectOne(qw);
        //8、如果存在，更新，如果不存在保存
        if (analysis != null) {
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setUpdated(new Date());
            analysisMapper.updateById(analysis);
        } else {
            analysis = new Analysis();
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(todayStr));
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysisMapper.insert(analysis);
        }
        return analysis;
    }

    public Integer queryCumulativeUsers() {
        return analysisMapper.queryCumulativeUsers();
    }

    public Analysis querySummary(Date now) {
        //5、根据当前时间查询AnalysisByDay数据
        LambdaQueryWrapper<Analysis> qw = Wrappers.<Analysis>lambdaQuery();
        qw.eq(Analysis::getRecordDate, DateUtil.format(now, "yyyy-MM-dd"));
        return analysisMapper.selectOne(qw);
    }

    //每一天的日期
    public CountVo getCount(String sd, String ed, Integer type) {
        LambdaQueryWrapper<Analysis> qw = new LambdaQueryWrapper<>();
        qw.between(Analysis::getRecordDate, sd, ed);
        List<Analysis> analyses = analysisMapper.selectList(qw);
        //System.out.println(analyses);
        List<Analysis> analyses1 = analysisMapper.findLastYear(sd, ed);
        List<ThisYear> list = new ArrayList<>();
        List<LastYear> lastList = new ArrayList<>();
        if (type == 101) {
            for (Analysis analysis : analyses) {
                ThisYear thisYear = new ThisYear();
                thisYear.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                thisYear.setAmount(analysis.getNumRegistered());
                list.add(thisYear);
            }
            for (Analysis analysis : analyses1) {
                LastYear lastYear = new LastYear();
                lastYear.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                lastYear.setAmount(analysis.getNumRegistered());
                lastList.add(lastYear);
            }
        } else if (type == 102) {
            for (Analysis analysis : analyses) {
                ThisYear thisYear = new ThisYear();
                thisYear.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                thisYear.setAmount(analysis.getNumActive());
                list.add(thisYear);
            }
            for (Analysis analysis : analyses1) {
                LastYear lastYear = new LastYear();
                lastYear.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                lastYear.setAmount(analysis.getNumActive());
                lastList.add(lastYear);
            }
        } else if (type == 103) {
            for (Analysis analysis : analyses) {
                ThisYear thisYear = new ThisYear();
                thisYear.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                thisYear.setAmount(analysis.getNumRetention1d());
                list.add(thisYear);
            }
            for (Analysis analysis : analyses1) {
                LastYear lastYear = new LastYear();
                lastYear.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                lastYear.setAmount(analysis.getNumRetention1d());
                lastList.add(lastYear);
            }
        }
        CountVo countVo = new CountVo();
        countVo.setThisYear(list);
        countVo.setLastYear(lastList);
        return countVo;
    }

    public Integer queryNumActive30(Integer days) {
        Integer count = analysisMapper.querynum30(days);
        return count;
    }

    public Integer querytoday(String type) {
        String today=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Integer count=analysisMapper.queryToday(today,type);
        return count;
    }
    public Integer querylasttoday(String type) {
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.DATE,-1);
        Date date=calendar.getTime();
        String today=new SimpleDateFormat("yyyy-MM-dd").format(date);
        Integer count=analysisMapper.queryToday(today,type);
        return count;
    }
}